package com.kyle.api.intercept;

import com.kyle.base.BaseInfoProperties;
import com.kyle.exceptions.GraceException;
import com.kyle.exceptions.MyCustomException;
import com.kyle.grace.result.ResponseStatusEnum;
import com.kyle.utils.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author：kyle_fu
 * @description: TODO
 * @Date：2024/2/14 12:52
 * @version: 1.0
 */
@Slf4j
public class SMSInterceptor extends BaseInfoProperties implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 获得用户ip
        String userIp = IPUtil.getRequestIp(request);
        //判断缓存中是否存在该ip
        boolean ipIsExist = redis.keyIsExist(MOBILE_SMSCODE + ":" + userIp);
        if (ipIsExist) {
            log.error("短信发送频率过快~~~~");
            GraceException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);
            return false;
        }
        /**
         * 如果存在，说明该ip已经发送过短信，返回false: 请求被拦截
         * 如果不存在，说明该ip没有发送过短信，返回true:放行,请求验证通过
         */
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
